import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const [maxX, maxY, maxZ] = [30, 6, 1];
const things: Array<THREE.Mesh | []> = [];

let scene: THREE.Scene; //创建场景
let camera: THREE.PerspectiveCamera;
export const init = (containerReference: string): THREE.WebGLRenderer => {
  const container = document.querySelector(containerReference) as HTMLDivElement;
  const renderer = new THREE.WebGLRenderer({
    antialias: true,
    alpha: true
  });
  camera = new THREE.PerspectiveCamera(
    75,
    container.clientWidth / container.clientHeight,
    0.001,
    1000
  );
  camera.position.z = 30;
  scene = new THREE.Scene(); //创建场景

  scene.background = new THREE.Color(0xdadaad);
  const axesHelper = new THREE.AxesHelper(30);
  scene.add(axesHelper);
  const controls = new OrbitControls(camera, renderer.domElement);
  // controls.enableDamping = true;
  controls.update();
  renderer.setSize(container.clientWidth, container.clientHeight);
  container.appendChild(renderer.domElement);

  for (let i = 0; i < maxX; i++) {
    things[i] = [];
    for (let j = 0; j < maxY; j++) {
      things[i][j] = [];
      for (let k = 0; k < maxZ; k++) {
        things[i][j][k] = addSphere(scene, i, j, k);
      }
    }
  }

  const render = (time: number) => {
    for (let i = 0; i < maxX; i++) {
      for (let j = 0; j < maxY; j++) {
        for (let k = 0; k < maxZ; k++) {
          // things[i][j][k].position.x = i + Math.sin(time / 1000 - i * 125);
          things[i][j][k].position.y =  j+Math.sin(time / 1000 - i * 125);
        }
      }
    }

    renderer.render(scene, camera);
  };
  renderer.setAnimationLoop(render);
  return renderer;
};

const addSphere = (scene: THREE.Scene, x: number = 0, y: number = 0, z: number = 0): THREE.Mesh => {
  const geometry = new THREE.SphereGeometry(0.1, 32, 16);
  const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
  const sphere = new THREE.Mesh(geometry, material);
  sphere.position.x = x;
  sphere.position.y = y;
  sphere.position.z = z;
  scene.add(sphere);
  return sphere;
};
